#include "fileListener.h"

void wsFileListener::onPing(const WebSocket& socket,const oatpp::String& message)
{
    OATPP_LOGD(TAG,"onPing");
    socket.sendPong(message);
}

void wsFileListener::onPong(const WebSocket& socket,const oatpp::String& message)
{
    OATPP_LOGD(TAG,"onPong");
}

void wsFileListener::onClose(const WebSocket& WebSocket,v_uint16 code,const oatpp::String& message)
{
    OATPP_LOGD(TAG, "onClose code=%d", code);
}

void wsFileListener::readMessage(const WebSocket& socket, v_uint8 opcode, p_char8 data, oatpp::v_io_size size)
{
    if(size==0)
    {
        std::string filePath=m_messageBuffer.toString();
        m_messageBuffer.setCurrentPosition(0);
        OATPP_LOGD(TAG,"Path=%s",filePath);
        std::ifstream iFile("/srv/www/shareDir/testDownload");
        if(!iFile.is_open())
        {
            socket.sendOneFrameText("false");
        }
        else
        {
            socket.sendOneFrameText("true");
        }
        iFile.close();
        oatpp::String fileData;
        fileData.loadFromFile(filePath.c_str());
        socket.sendOneFrameBinary(fileData);
    }
    else if(size>0)
    {
        OATPP_LOGD("TAG","receive frame");
        m_messageBuffer.writeSimple(data,size);
    }
}

std::atomic<v_int32> wsFileInstanceListener::SOCKETS(0);

void wsFileInstanceListener::onAfterCreate(const oatpp::websocket::WebSocket& socket, const std::shared_ptr<const ParameterMap>& params) {

  SOCKETS ++;
  OATPP_LOGD(TAG, "New Incoming Connection. Connection count=%d", SOCKETS.load());

  /* In this particular case we create one WSListener per each connection */
  /* Which may be redundant in many cases */
  socket.setListener(std::make_shared<wsFileListener>());
}

void wsFileInstanceListener::onBeforeDestroy(const oatpp::websocket::WebSocket& socket) {

  SOCKETS --;
  OATPP_LOGD(TAG, "Connection closed. Connection count=%d", SOCKETS.load());

}